package org.shop.controller.app;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.Merchant;
import org.shop.entity.Users;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.MerchantService;
import org.shop.service.UserService;
import org.shop.util.CommonUtil;
import org.shop.util.DateUtils;
import org.shop.util.FtpUtil2;
import org.shop.util.ObjUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Controller
public class MerchantController {
	private static Logger logger = LogManager.getLogger(MerchantController.class);
	@Autowired
	private MerchantService merchantService;
	@Autowired
    private UserService userService;
	
	
	/**
	 * 店铺认证
	 * @param req
	 * @return
	 */
	@RequestMapping("app/authenticationShop")
	@ResponseBody
	public Map<String, Object> authenticationShop(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		String realName = req.getParameter("realName");
		String idNo = req.getParameter("idNo");
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			Users user = new Users();
			user.setRealName(realName);
			user.setIdNo(idNo);
			userService.updateByPrimaryKeySelective(user);
			map.put("state", 1);
            map.put("msg", "提交成功");
		} catch(Exception e) {
			logger.error(e);
			map.put("state", 0);
            map.put("msg", "提交失败");
		}
		
		return map;
	}
	/**
	 * 获取申请图片
	 * @param req
	 * @return
	 */
	@RequestMapping("app/getApplyPhoto")
	public void getGoodsPhoto(HttpServletRequest req,HttpServletResponse res){
		String photoStr=req.getParameter("photoUrl");
		OutputStream os =null;
		InputStream is =null;
		FTPClient ftpClient =null;
		try {
			res.setContentType("image/jpg");
			ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"));
			if(photoStr.lastIndexOf("/")>0){
				FtpUtil2.changeWorkingDirectory(photoStr.substring(0, photoStr.lastIndexOf("/")), ftpClient);
				is=FtpUtil2.retrieveFileStream(photoStr.substring(photoStr.lastIndexOf("/")+1,photoStr.length()), ftpClient);
			}else{
				is=FtpUtil2.retrieveFileStream(photoStr, ftpClient);
			}
			os=res.getOutputStream();
			byte[] buf = new byte[1024];
            while (true) {
                int read = 0;
                if (is != null) {
                    read = is.read(buf);
                }
                if (read == -1) {
                    break;
                }
                os.write(buf, 0, read);
            }
            os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(ftpClient!=null){
					FtpUtil2.closeConnection(ftpClient);
				}
			} catch (Exception e) {
				ftpClient=null;
			} 
			try {
				os.close();
			} catch (IOException e) {
				os=null;
			} 
			try {
				is.close();
			} catch (IOException e) {
				is=null;
			}
		}
	}
	
	/**
	 * 学生申请开店
	 * @param req
	 * @return
	 */
	@RequestMapping("app/studentApplyShop")
	@ResponseBody
	public Map<String, Object> studentApplyShop(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		String merchantName = req.getParameter("merchantName");
		String merchartIntro = req.getParameter("merchartIntro");
		String merchantPhone = req.getParameter("merchantPhone");
		String merchartClassifyId = req.getParameter("merchartClassifyId");
		String handIdcardImg = req.getParameter("handIdcardImg");
		String studentIdImg = req.getParameter("studentIdImg");
		String merchartHeadPortrait = req.getParameter("merchartHeadPortrait");
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			Map<String, Object> paramMap=new HashMap<String, Object>();
			paramMap.put("merchantName", merchantName);
			int count=merchantService.verifyMerchantName(paramMap);
			if(count > 0) {
				map.put("state", 2);
				map.put("msg", "店铺名已存在");
			}else {
				Merchant merchant = new Merchant();
				merchant.setMerchantName(merchantName);
				merchant.setMerchartIntro(merchartIntro);
				merchant.setMerchantPhone(merchantPhone);
				merchant.setMerchartClassifyId(Long.parseLong(merchartClassifyId));
				merchant.setHandIdcardImg(handIdcardImg);
				merchant.setStudentIdImg(studentIdImg);
				merchant.setMerchartHeadPortrait(merchartHeadPortrait);
				merchant.setSchoolId(ud.getSchoolId());
				merchant.setMerchantType((byte)2);
				merchantService.insertSelective(merchant);
				Users user = new Users();
				user.setUserId(ud.getUserId());
				user.setMerchantId(merchant.getMerchantId());
				userService.updateByPrimaryKeySelective(user);
				map.put("state", 1);
				map.put("msg", "申请成功，请等待审核");
			}
		} catch(Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put("state", 0);
			map.put("msg", "申请失败");
		}
		
		return map;
	}
	
	
}
